package com.gin.kotlin.no_gay_alliance.activity

import android.Manifest
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Build
import android.text.InputType
import android.util.Log
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import androidx.core.view.MenuProvider
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.activity.pm.PrivateMessageActivity
import com.gin.kotlin.no_gay_alliance.activity.replyhistory.ReplyHistoryActivity
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.argument.AppReleaseArgument
import com.gin.kotlin.no_gay_alliance.argument.ReplyHistoryArgument
import com.gin.kotlin.no_gay_alliance.argument.TopicListArgument
import com.gin.kotlin.no_gay_alliance.argument.TopicListArgument.Type.FAVOR_FOLDER
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingActivity
import com.gin.kotlin.no_gay_alliance.base.AlertDialogUtils
import com.gin.kotlin.no_gay_alliance.base.BuglyUtils
import com.gin.kotlin.no_gay_alliance.base.ClipboardUtils
import com.gin.kotlin.no_gay_alliance.base.DownloadUtils
import com.gin.kotlin.no_gay_alliance.base.FragmentStateContainer
import com.gin.kotlin.no_gay_alliance.base.InputMethodUtils
import com.gin.kotlin.no_gay_alliance.base.MyHandler
import com.gin.kotlin.no_gay_alliance.callback.SCallback
import com.gin.kotlin.no_gay_alliance.databinding.ActivityMainBinding
import com.gin.kotlin.no_gay_alliance.fragment.main.MainCommunityFragment
import com.gin.kotlin.no_gay_alliance.fragment.main.MainMeFragment
import com.gin.kotlin.no_gay_alliance.fragment.main.MainSettingFragment
import com.gin.kotlin.no_gay_alliance.model.AppReleaseModel
import com.gin.kotlin.no_gay_alliance.provider.thirdparty.AppReleaseProvider
import com.gin.kotlin.no_gay_alliance.store.RuntimeData
import com.gin.nga.enums.NgaPhpApi
import com.google.android.material.navigation.NavigationBarView
import okhttp3.Call
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import java.io.IOException

class MainActivity : AbstractBindingActivity<ActivityMainBinding>(), NavigationBarView.OnItemSelectedListener {

    private lateinit var fragmentStateContainers: List<FragmentStateContainer>
    private var currentFragment: Fragment? = null

    /**
     * 解析意图
     * @param intent Intent?
     */
    override fun handleIntent(intent: Intent) {
    }

    /**
     * 装载右上角菜单, 使用 [MenuInflater.inflate] 方法
     * @param menu Menu
     * @param menuInflater MenuInflater
     */
    override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) {
        //清空菜单
        menu.clear()

        //先装载当前Fragment的菜单
        (currentFragment as? MenuProvider)?.onCreateMenu(menu, menuInflater)

        //装载通用菜单 提醒、私信、主题浏览历史、举报记录、回复历史
        menuInflater.inflate(R.menu.common_menu, menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // 先由Fragment处理
        if ((currentFragment as? MenuProvider)?.onMenuItemSelected(item) == true) {
            return true
        }
        return handleCommonOptionsItemSelected(this, handler, item)
    }

    /**
     * onCreate方法的后续操作，如 [AbstractBindingActivity.registerLauncher]， 或 [AbstractBindingActivity.attachTabLayout]
     */
    override fun onCreate() {
        // 请求通知信息的发送权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 0)
        }
        val b = this.b ?: throw RuntimeException("启动错误")

        //  FragmentState
        fragmentStateContainers = listOf(
            FragmentStateContainer(resources.getText(R.string.mi_main_navi_me), R.id.mi_main_navi_me) { MainMeFragment() },
            FragmentStateContainer(resources.getText(R.string.mi_main_navi_community), R.id.mi_main_navi_community) { MainCommunityFragment() },
            FragmentStateContainer(resources.getText(R.string.mi_main_navi_setting), R.id.mi_main_navi_setting) { MainSettingFragment() },
        )
        // 为ViewPager2设置适配器
        b.viewPager2MainTab.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount() = fragmentStateContainers.size
            override fun createFragment(position: Int) = FragmentStateContainer.newInstance(fragmentStateContainers, position)
        }

        // 禁用ViewPager2的左右滑动，只允许通过点击导航按钮切换
        b.viewPager2MainTab.setUserInputEnabled(false)

        // 点击导航按钮时，同步切换ViewPager2的页面
        b.bottomNavi.setOnItemSelectedListener(this)

        // 设置初始位置
        val index = 1
        setCurrent(index)
        b.bottomNavi.menu.getItem(index).setChecked(true)

        // bugly请求授权
        BuglyUtils.check(this)


        checkAppRelease()
    }

    override fun onResume() {
        super.onResume()
        // 必须延迟一会才能获取到剪贴板内容
        uiDelayed(300) { checkClipboard() }
    }

    /**
     * 检查剪贴板，如果发现可打开的链接，弹出提示
     */
    private fun checkClipboard() {
        val context = this
        val url = ClipboardUtils.getText(0, context) ?: return
        Log.i(TAG, "发现链接: $url")
        val httpUrl = url.toHttpUrlOrNull() ?: return
        val path = httpUrl.pathSegments.firstOrNull() ?: return
        val userId = httpUrl.queryParameter("uid")?.toLongOrNull()?.takeIf { it > 0 }
        val username = httpUrl.queryParameter("username")?.takeIf { it.isNotEmpty() }
        // 是否为用户中心链接
        val isUserCenter = httpUrl.queryParameter("func") == "ucp" && (userId != null || username != null)
        when {
            // 打开 版面 / 合集
            path.equals(NgaPhpApi.THREAD, true) -> showUrlDialog("版面/合集", url) { TopicListActivity.startActivity(context, url) }
            // 打开 主题
            path.equals(NgaPhpApi.READ, true) -> showUrlDialog("主题/回复", url) { ReplyListActivity.startActivity(context, url) }
            // 打开用户中心
            path.equals(NgaPhpApi.NUKE, true) && isUserCenter -> showUrlDialog("用户中心", url) { UserCenterActivity.startActivity(context, url) }
        }
    }

    /**
     * 打开一个弹窗，确认是否使用本APP打开链接
     * @param type 链接类型
     * @param url url
     * @param handle 处理url的方法
     */
    private fun showUrlDialog(type: String, url: String, handle: (url: String) -> Unit) {
        val context = this
        val listener = DialogInterface.OnClickListener { _, which ->
            when (which) {
                DialogInterface.BUTTON_POSITIVE -> handle(url)
                DialogInterface.BUTTON_NEUTRAL -> ClipboardUtils.clear(context)
            }
        }
        AlertDialogUtils.builder(context, "发现 $type 链接，是否打开？", url, listener = listener).setNeutralButton("清空", listener).show()
    }


    /**
     * 检查发行版更新
     */
    private fun checkAppRelease() {
        val context = this
        AppReleaseProvider.getInstance().enqueue(AppReleaseArgument(), ignoreCache = true, object : SCallback<List<AppReleaseModel>> {
            override fun onSuccess(data: List<AppReleaseModel>) {
                val ignoredTagName = RuntimeData.getInstance().ignoredTagName
                data.getOrNull(0)?.takeIf { ignoredTagName < it.tagName!! && App.INSTANCE.versionName < it.tagName!! }?.also { appRelease ->
                    val tagName = appRelease.tagName!!
                    // 弹窗询问是否下载
                    val messageBuilder = StringBuilder(tagName)
                        .append(if (appRelease.preRelease == true) " [预览版]" else " ")
                        .append(" 是否下载？更新内容:\n\n")
                        .append(appRelease.body)

                    val listener = DialogInterface.OnClickListener { _, which ->
                        when (which) {
                            DialogInterface.BUTTON_POSITIVE -> {
                                DownloadUtils.enqueue(context, listOf(DownloadUtils.DownloadOption(appRelease.obtainUrl()!!, appRelease.obtainFilename()!!)))
                                RuntimeData.getInstance().ignoredTagName = tagName
                                toast("开始下载")
                            }
                            // 忽略
                            DialogInterface.BUTTON_NEUTRAL -> {
                                RuntimeData.getInstance().ignoredTagName = tagName
                                toast("已忽略版本: $tagName")
                            }
                        }
                    }
                    handler?.post { AlertDialogUtils.builder(context, "发现新版本", messageBuilder.toString(), listener = listener).setNeutralButton("忽略", listener).show() }
                }
            }

            override fun onFailure(call: Call, e: IOException) {
                toastLong("版本查询失败: ${e.localizedMessage}")
            }
        })
    }


    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        FragmentStateContainer.findIndexById(fragmentStateContainers, item.itemId)?.also { setCurrent(it) }
        return true
    }

    private fun setCurrent(index: Int) {
        b?.viewPager2MainTab?.setCurrentItem(index, false)
        setToolbarTitle(fragmentStateContainers[index].title.toString())
    }

    /**
     * 当fragment可见时设置其为当前Fragment
     * @param fragment Fragment?
     */
    fun onFragmentVisible(fragment: Fragment) {
        this.currentFragment = fragment
        // 请求重新创建菜单
        supportInvalidateOptionsMenu()
    }


    companion object {
        /**
         * 处理通用菜单项的点击事件
         * @param context Context
         * @param handler MyHandler?
         * @param item MenuItem
         * @return Boolean
         */
        fun handleCommonOptionsItemSelected(context: Context, handler: MyHandler?, item: MenuItem) = when (item.itemId) {
            R.id.mi_notice -> {
                NoticeActivity.startActivity(context)
                true
            }

            R.id.mi_private_message -> {
                PrivateMessageActivity.startActivity(context)
                true
            }

            R.id.mi_topic_history -> {
                TopicHistoryActivity.start(context)
                true
            }

            // 查询回复历史
            R.id.mi_reply_history -> {
                ReplyHistoryActivity.start(context, ReplyHistoryArgument())
                true
            }

            // 举报历史
            R.id.mi_report_history -> {
                ReportHistoryActivity.start(context)
                true
            }
            // 通过用户名找人
            R.id.mi_find_user -> {
                val editText = EditText(context)
                editText.hint = "请输入准确的用户名"
                editText.imeOptions = EditorInfo.IME_ACTION_SEARCH
                editText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
                editText.requestFocus()
                editText.selectAll()


                val dialog = AlertDialogUtils.builder(context, "找人", contentView = editText, listener = { _, which ->
                    val username = editText.text.toString().trim()
                    if (which == DialogInterface.BUTTON_POSITIVE && username.isNotEmpty()) UserCenterActivity.startActivity(context, username = username)
                }).show()

                editText.setOnEditorActionListener { v, actionId, _ ->
                    val username = v?.text.toString().trim()
                    if (actionId == EditorInfo.IME_ACTION_SEARCH && username.isNotEmpty()) {
                        dialog.hide()
                        UserCenterActivity.startActivity(context, username = username)
                    }
                    true
                }

                handler?.postDelayed({ InputMethodUtils.show(editText) }, 200)
                true
            }

            R.id.mi_favor_folder -> {
                TopicListActivity.startActivity(context, TopicListArgument(FAVOR_FOLDER, authorUid = App.INSTANCE.account.userId))
                true
            }

            else -> {
                Log.w(MainActivity::class.java.simpleName, "未识别的菜单: ${item.itemId}")
                false
            }
        }
    }

}
